package com.yj.springbootmiaosha.controller;

import com.yj.springbootmiaosha.zkLock.ZkLock;
import lombok.extern.slf4j.Slf4j;
import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.locks.InterProcessMutex;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.springframework.context.annotation.Bean;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

@RestController
@Slf4j
public class ZookeeperLockController {


    static String key = "order";

    @GetMapping("zookeeperLock")
    public String zookeeperLock() {
        log.info("我已经进入方法！");
        try (ZkLock zkLock = new ZkLock()) {
            boolean result = zkLock.getLock(key);
            if (result) {
                log.info("我已经获取到锁！");
            }
            // 模拟业务方法
            Thread.sleep(10000);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "方法执行结束！";
    }

    @Resource
    private CuratorFramework client;

    @GetMapping("curatorLock")
    public String curatorLock() throws Exception {
        log.info("我已经进入了方法！");

        InterProcessMutex lock = new InterProcessMutex(client, "/order");
        if (lock.acquire(30, TimeUnit.SECONDS)) {
            try {
                // do some work inside of the critical section here
                log.info("获取到了锁！");
                Thread.sleep(6000);
            } finally {
                log.info("释放了锁！");
                lock.release();
            }
        }
        return "方法执行结束！";
    }

    @Bean(initMethod = "start",destroyMethod = "close")
    public CuratorFramework curatorFramework(){
        RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);
        CuratorFramework client = CuratorFrameworkFactory.newClient("192.168.152.12:2181", retryPolicy);
        return client;
    }
}
